package com.koron.common.core.filter;

import com.github.pagehelper.PageHelper;
import com.koron.bean.app.AppBean;
import com.koron.bean.app.AppSimpleBean;
import com.koron.bean.system.staff.Constant;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.system.SystemCacheUtil;
import com.koron.common.core.config.ThreadLocalContext;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName StaffInfoFilter
 * @description
 * @Author zhouj
 * @Date 2021/7/15 11:51
 */
@Component
@RefreshScope
public class CoreLoginInfoFilter implements Filter {

    @Value("${isNeedLogin}")
    private Boolean isNeedLogin;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //在DispatcherServlet之前执行 移除插件信息，防止线程污染
        PageHelper.clearPage();
        ThreadLocalContext.clear();

        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper((HttpServletRequest) request);
        }

        HttpServletRequest req = (HttpServletRequest) request;

        //1.1 从redis获取用户信息
        String token = req.getHeader(Constant.JWT_TOKEN);
        //水司权限 不做控制，在网关层做处理
        //以下四个动态参数皆为动态,由请求传递(无状态)
        //动态水司
        String currDS = req.getHeader(Constant.DYNAMIC_DATA_SOURCE);
        //动态组织
        String currOrg = req.getHeader(Constant.DYNAMIC_AGENT_ORG);
        //动态领导
        String currLeader = req.getHeader(Constant.DYNAMIC_LEADER);
        //动态领导组织
        String currLeaderOrg = req.getHeader(Constant.DYNAMIC_LEADER_ORG);
        //语言
        String currLanguage = req.getHeader(Constant.LANGUAGE);
        //直接设置到用户里面
        EamUser redisAgentLeaderUser = null;
        EamUser user = new EamUser();
        //是否需要登录
        if (isNeedLogin) {
            if (StringUtils.isNotEmpty(token)) {
                String account = SystemCacheUtil.verifyToken(token);
                if (StringUtils.isNotEmpty(account)) {
                    //根据账号查询redis中登录用户数据
                    EamUser redisUser = SystemCacheUtil.getRedisUser(account);
                    if (!Objects.isNull(redisUser)) {
                        List<String> tokenList = redisUser.getTokenList();
                        if (CollectionUtils.isNotEmpty(tokenList) && tokenList.contains(token)) {
                            user = redisUser;
                        }
                    }
                }
            }
        } else {
            if (StringUtils.isEmpty(currDS)) {
                currDS = "water_02";
            }
        }
        if (StringUtils.isEmpty(user.getAccount())) {
            String account = "test";
            if (StringUtils.isNotEmpty(token)) {
                String a = SystemCacheUtil.verifyToken(token);
                account = StringUtils.isNotEmpty(a) ? a : account;
            }
            //设置当前水司
            user.setAccount(account);
            EamUser redisUser = SystemCacheUtil.getRedisUser(user.getAccount());
            if (!Objects.isNull(redisUser)) {
                user = redisUser;
            } else {
                user = defaultUser();
            }
        }
        //判断是否正在代理领导,通过currLeader字段
        if (StringUtils.isNotEmpty(currLeader) && !currLeader.equals(user.getAccount())) {
            //非本人
            redisAgentLeaderUser = SystemCacheUtil.getAgentLeaderRedisUser(currLeader, user.getAccount());
            if (!Objects.isNull(redisAgentLeaderUser)) {
                redisAgentLeaderUser.setCurrLeaderOrg(currLeaderOrg);
                redisAgentLeaderUser.setCurrDs(currDS);
                redisAgentLeaderUser.setLanguage(currLanguage);
                redisAgentLeaderUser.setAgent(user);
            }
        }

        user.setCurrDs(currDS);
        //设置当前组织
        user.setCurrOrg(currOrg);
        //设置当前身份
        user.setCurrLeader(currLeader);
        //设置当前语种
        user.setLanguage(currLanguage);
        if (Objects.isNull(redisAgentLeaderUser)) {
            ThreadLocalContext.set(user);
            ThreadLocalContext.setApp(getCurrApp(user));
        } else {
            ThreadLocalContext.set(redisAgentLeaderUser);
            ThreadLocalContext.setApp(getCurrApp(redisAgentLeaderUser));
        }
        //获取request请求中的流，将取出来的字符串保存在缓存中，同时再将该字符串再次转换成流，然后把它放入到新request对象中。
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
        // 在视图页面返回给客户端之前执行，但是执行顺序在Interceptor之后
        ThreadLocalContext.clear();
        PageHelper.clearPage();
    }

    AppBean getCurrApp(EamUser eamUser) {

        String currDs = eamUser.getCurrDs();

        List<AppSimpleBean> appSimpleBeanList = eamUser.getAppSimpleBeanList();
        if (CollectionUtils.isEmpty(appSimpleBeanList)) {
            return null;
        }
        for (AppSimpleBean appSimpleBean : appSimpleBeanList) {
            if (StringUtils.equals(currDs, appSimpleBean.getAppMark())) {
                AppBean appBeanTemp = new AppBean();
                appBeanTemp.setId(appSimpleBean.getAppId());
                appBeanTemp.setCode(appSimpleBean.getAppCode());
                appBeanTemp.setMark(appSimpleBean.getAppMark());
                appBeanTemp.setName(appSimpleBean.getAppName());
                appBeanTemp.setSign(appSimpleBean.getSign());
                appBeanTemp.setStatus(appSimpleBean.getStatus());

                return appBeanTemp;
            }
        }
        return null;
    }

    public EamUser defaultUser() {
        EamUser user = new EamUser();
        user.setId("test");
        user.setName("测试");
        user.setAccount("test");
        user.setNamePy("test");
        user.setOrgId("db3aa58e934449db8906726e1e23694c");
        user.setOrgName("测试组织");
        user.setAppId("8e7e09b125ea4dbc8d0515564ceda01d");
        user.setAppName("测试水司");
        user.setPhone("13005409539");
        user.setDeptId("db3aa58e934449db8906726e1e23694c");
        user.setDeptName("测试组织");
        return user;
    }
}
